package com.fwj.threadexample;

/**
 * 多线程卖票问题
 *
 * @author stone.feng
 * @since 2019-03-02
 */
public class ThreadDemo {

    /**
     * 加锁Runnable版
     */
    public static class myRunnable implements Runnable {

        private int ticket = 1000;

        @Override
        public void run() {
            synchronized (this) {
                while (true) {
                    if (ticket > 0) {
                        System.out.println(Thread.currentThread().getName() + "正在销售" + ticket + "张");
                        ticket--;
                    } else {
                        System.out.println(Thread.currentThread().getName() + "销售完毕");
                        break;
                    }
                }
            }

        }
    }

    public static class myThread extends Thread {

        private static int ticket = 1000;

        private static Object obj = new Object();

        public myThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            synchronized (obj) {
                while (true) {
                    if (ticket > 0) {
                        System.out.println(Thread.currentThread().getName() + "正在销售" + ticket + "张");
                        ticket--;
                    } else {
                        System.out.println(Thread.currentThread().getName() + "销售完毕");
                        break;
                    }
                }
            }

        }
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i <= 9) {
                new myThread(Thread.currentThread().getName() + "窗口00" + i).start();
            } else {
                new myThread("窗口010").start();
            }
        }
    }

}